//
//  GroupDetails.m
//  SelfDriving
//
//  Created by apple on 16/4/6.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "GroupDetails.h"
#import "GroupDCell.h"
#import "GroupChatVC.h"
#import "SVProgressHUD.h"
#import "GroupDetailsEditVC.h"
#import "NewConversationVC.h"
#import "GroupListVC.h"
#import "ReportViewController.h"
@interface GroupDetails()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate,TCResultGroupDelegate,TCResultNoneDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UISwitch *swtIsGetMessage;
@property (weak, nonatomic) IBOutlet UIButton *delbtn;
@property (weak, nonatomic) IBOutlet UITableView *table;

@end
@implementation GroupDetails{
    TCGroup *group;
    int delType;//删除状态
    LoginResponseModel *user;
    NSMutableArray *ary;
}
-(void)viewWillAppear:(BOOL)animated{
//        [[ThinkChat instance] getConversationDetail:_session.ID delegate:self];
    [self initdata];
}
-(void)initdata{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:_session.ID forKey:@"sessionid"];
    [[BusinessService shareInstance]detail:dic success:^(id result) {
        user = result;
        if([user isKindOfClass:[LoginResponseModel class]]){
            //xhw2018-1-25
            if ([user.role intValue]==1) {
                NSLog(@"删除");
            }
            else {
                [_delbtn setTitle:@"退出" forState:UIControlStateNormal];
            }
            
            TCUser *user1 = [[TCUser alloc]init];
            user1.head = @"jia";
            TCUser *user2 = [[TCUser alloc]init];
            user2.head = @"jian";
            ary = [[NSMutableArray alloc]init];
            [ary addObjectsFromArray:user.list];
            if (!_isqrcode) {
                [ary addObject:user1];
                [ary addObject:user2];
            }
            [_table reloadData];
        } else{
            [SVProgressHUD showErrorWithStatus:@"无效的群"];
            [_table setUserInteractionEnabled:NO];
            [_delbtn setUserInteractionEnabled:NO];
        }
    } failure:^(id result) {
        
    }];
}
-(void)viewDidLoad{
    if (_isqrcode) {
         _delbtn.hidden = YES;
        _swtIsGetMessage.userInteractionEnabled = NO;
        BaseButton *jrbtn = [[BaseButton alloc]initWithFrame:CGRectMake(0, SCRE_HEIGHT-45, SCRE_WIDTH, 45)];
        
        [jrbtn setTitle:@"进入" forState:UIControlStateNormal];
        jrbtn.backgroundColor = [UIColor blackColor];
        [jrbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        jrbtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [jrbtn addTarget:self action:@selector(jinruqun:) forControlEvents:UIControlEventTouchUpInside];
        jrbtn.layer.zPosition = 99;
        [self.view addSubview:jrbtn];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:_session.ID forKey:@"sessionid"];
        
        
#pragma mark - 6月9日 改成：直接进入聊天室
//        [[BusinessService shareInstance]detail:dic success:^(id result) {
//            LoginResponseModel *users = result;
//            if([users isKindOfClass:[LoginResponseModel class]]){
//                for (NSMutableDictionary *img  in users.list) {
//                    if ([[img objectForKey:@"uid"] intValue ]==[[AppDelegate shareDelegate].user.uid intValue]) {
//                        _delbtn.hidden = NO;
//                        jrbtn.hidden = YES;
//                    }
//                }
//            }
//        } failure:^(id result) {
//        }];
    }
}
#pragma mark 进入群
-(void)jinruqun:(BaseButton *)btn{
    
    TCSession *model = [[TCSession alloc]init];
    model.typeChat = 200;
    model.name = user.name;
    model.ID = _session.ID;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    GroupChatVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupChatVC"];
    searchResultDetailController.tcs = model;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];

    
    
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    [dic setObject:[AppDelegate shareDelegate].user.uid forKey:@"uids"];
//    [dic setObject:_session.ID forKey:@"sessionid"];
//    [[BusinessService shareInstance]addUserToSession:dic success:^(id result) {
//        [self.navigationController popViewControllerAnimated:YES];
//        return ;
//    } failure:^(id result) {
//        [SVProgressHUD showErrorWithStatus:result];
//    }];

    
}

#pragma mark - TCResultGroupDelegate

- (void)tcResultGroup:(TCGroup *)itemG error:(TCError *)itemE {
    if (!itemE) {
        
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
//        return 3; //xhw2018-2-5加
        if (section == 1) {
            return 3;
        }
        else {
            if ([user.role intValue]==1) {
                return 2;
            }
            else {
                return 3;
            }
        }
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        float th = ary.count/4.00;
        int h = ceilf(th);
        h = h==0?1:h;
        return h*(SCRE_WIDTH/4);
    }else{
        return 40;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //    if (section == 2) {
    //        return 80;
    //    }
    return 8;
}
//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    if (section == 2) {
//        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, 80)];
//        view.backgroundColor = [UIColor clearColor];
//        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 40, SCRE_WIDTH, 40)];
//        btn.backgroundColor = [UIColor blackColor];
//        [btn setTintColor:[UIColor whiteColor]];
//        [btn addTarget:self action:@selector(DelOutAction:) forControlEvents:UIControlEventTouchUpInside];
//        btn.titleLabel.font = [UIFont systemFontOfSize:15];
//        [btn setTitle:@"删除并退出" forState:UIControlStateNormal];
//        [view addSubview:btn];
//        return view;
//    }
//    return nil;
//}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        for (UIView *view  in  [cell.contentView subviews]){
            [view removeFromSuperview];
        }
        float th = ary.count/4.00;
        int h = ceilf(th);
        h = h==0?1:h;
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        UICollectionView *collction = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, h*(SCRE_WIDTH/4)) collectionViewLayout:flowLayout];
        collction.delegate = self;
        collction.dataSource = self;
        collction.backgroundColor = [UIColor clearColor];
        [collction registerClass:[GroupDCell class] forCellWithReuseIdentifier:@"GroupDCell"];
        [cell.contentView addSubview:collction];
        CGRect r =  cell.frame;
        r.size.height = collction.frame.size.height+10;
        cell.frame = r;
        return cell;
    }
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"会话名称";
            cell.detailTextLabel.text = user.name;
            [_deletegae upname:user.name];
        }
        if (indexPath.row == 1) {
            cell.textLabel.text = @"二维码";
            UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 50, 5, 30, 30)];
            //            img.image = [UIImage imageNamed:@"qlxq2code"];
            [ValidateHelper setImage:user.qrcodelarge img:img istoux:NO];
            cell.accessoryView = img;
        }
        if (indexPath.row == 2) {
            cell.textLabel.text = @"我在本群名称";
            cell.detailTextLabel.text = user.nickname.length==0?[AppDelegate shareDelegate].user.nickname:user.nickname;
        }
    }
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"新消息提醒";
            [_swtIsGetMessage setOn:[user.getmsg intValue]];
            cell.accessoryView = _swtIsGetMessage;
        }
        if (indexPath.row == 1) {
            cell.textLabel.text = @"清除聊天记录";
        }
        if (indexPath.row == 2) {
            cell.textLabel.text = @"举报";
        }
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_isqrcode) {
        return;
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                         bundle:[NSBundle mainBundle]];
            GroupDetailsEditVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupDetailsEditVC"];
            searchResultDetailController.sessionid = user.id;
            [self.navigationController pushViewController:searchResultDetailController animated:YES];
        }
        if (indexPath.row == 1) {
            [self picenlarge];
        }
        if (indexPath.row == 2) {
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                         bundle:[NSBundle mainBundle]];
            GroupDetailsEditVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupDetailsEditVC"];
            
            searchResultDetailController.sessionid = user.id;
            searchResultDetailController.type = @"我在本群名称";
            [self.navigationController pushViewController:searchResultDetailController animated:YES];
        }
    }
    if (indexPath.section == 2) {
        if (indexPath.row == 1) {
//            [[AppDelegate shareDelegate] clearSessionID:user.id typeChat:forChatTypeGroup];
            [[AppDelegate shareDelegate] clearSessionID:user.id typeChat:forChatTypeRoom];//xhw2018-1-26改
            [SVProgressHUD showSuccessWithStatus:@"清理成功"];
        }
        //xhw2018-1-21加
        if (indexPath.row == 2) {
            if ([user.role intValue]==1) {
                [SVProgressHUD showInfoWithStatus:@"您不能举报自己的群"];
                return;
            }
            else {

            }
            
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                         bundle:[NSBundle mainBundle]];
            ReportViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"ReportViewController"];

            searchResultDetailController.type = @"6";
            searchResultDetailController.content = _session.ID; //举报的群id
            
            [self.navigationController pushViewController:searchResultDetailController animated:YES];
        }
    }
    
}

#pragma  mark uicollectionViewDeleage
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return ary.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    TCUser *usert = [ary objectAtIndex:indexPath.row];
    if ([usert isKindOfClass:[TCUser class]]) {
        if ([usert.head isEqualToString:@"jia"]) {
            GroupDCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GroupDCell" forIndexPath:indexPath];
            if([[cell.contentView.subviews lastObject] isKindOfClass:[UIView class]]){
                [[cell.contentView.subviews lastObject] removeFromSuperview];
            }
            UIImageView *head = [[UIImageView alloc]initWithFrame:CGRectMake(cell.frame.size.width/2-35/2, cell.frame.size.height/2-35/2,35, 35)];
            head.image = [UIImage imageNamed:@"qlxq+"];
            [cell.contentView addSubview:head];
            
            UIButton *btn = [[UIButton alloc]initWithFrame:head.frame];
            [cell addSubview:btn];
            [btn addTarget:self action:@selector(jiaAction:) forControlEvents:UIControlEventTouchUpInside];
            cell.backgroundColor = colorBG;
            return  cell;
        }else if ([usert.head isEqualToString:@"jian"]){
            GroupDCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GroupDCell" forIndexPath:indexPath];
            if([[cell.contentView.subviews lastObject] isKindOfClass:[UIView class]]){
                [[cell.contentView.subviews lastObject] removeFromSuperview];
            }
            UIImageView *head = [[UIImageView alloc]initWithFrame:CGRectMake(cell.frame.size.width/2-35/2, cell.frame.size.height/2-35/2,35, 35)];
            head.image = [UIImage imageNamed:@"qlxq-"];
            [cell.contentView addSubview:head];
            
            UIButton *btn = [[UIButton alloc]initWithFrame:head.frame];
            [cell.contentView addSubview:btn];
            [btn addTarget:self action:@selector(jianAction:) forControlEvents:UIControlEventTouchUpInside];
            cell.backgroundColor = colorBG;
            return  cell;
        }
    }else{
        NSMutableDictionary *dic = [ary objectAtIndex:indexPath.row];
        LoginResponseModel *user1 = [[LoginResponseModel alloc]init];
        [user1 serializationWithDictionary:dic];
        GroupDCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GroupDCell" forIndexPath:indexPath];
        if([[cell.contentView.subviews lastObject] isKindOfClass:[UIView class]]){
            [[cell.contentView.subviews lastObject] removeFromSuperview];
        }
        UIImageView *head = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
        head.clipsToBounds = YES;
        
        [ValidateHelper setImage:user1.headlarge img:head istoux:YES];
        [cell.contentView addSubview:head];
        if (delType==1) {
            BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
            [btn setImage:[UIImage imageNamed:@"delete_d"] forState:UIControlStateNormal];
            [cell.contentView addSubview:btn];
            btn.model = user1;
            [btn setImageEdgeInsets:UIEdgeInsetsMake(-20, -20, 0, 0)];
            [btn addTarget:self action:@selector(delActions:) forControlEvents:UIControlEventTouchUpInside];
        }
        return cell;
        
    }
    return  nil;
    
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.f;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(3,3, 3, 3);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake(SCRE_WIDTH/4-3,SCRE_WIDTH/4-3);
    return size;
}
#pragma  mark 添加人
-(void)jiaAction:(UIButton *)btn{
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    NewConversationVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"NewConversationVC"];
    searchResultDetailController.type = YES;
    searchResultDetailController.sessionid = user.id;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}

#pragma  mark 删除人状态
-(void)jianAction:(UIButton *)btn{
    delType = delType==0?1:0;
    [_table reloadData];
    
}
#pragma mark 删除群组人
-(void)delActions:(BaseButton *)btn{
    LoginResponseModel *user1 = btn.model;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:user1.uid forKey:@"fuid"];
    [dic setObject:user.id forKey:@"sessionid"];
    [[BusinessService shareInstance]remove:dic success:^(id result) {
        [self initdata];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
    
    
    
    
}

#pragma mark 图片放大
-(void)picenlarge {
    NSMutableArray  *imgdata = [[NSMutableArray alloc]init];
    ZLPhotoPickerBrowserPhoto *photo = [[ZLPhotoPickerBrowserPhoto alloc] init];
    photo.photoURL = [NSURL URLWithString:user.qrcodesmall];
    [imgdata addObject:photo];
    
    // 图片游览器
    ZLPhotoPickerBrowserViewController *pickerBrowser = [[ZLPhotoPickerBrowserViewController alloc] init];
    // 数据源/delegate
    //    pickerBrowser.delegate = self;
    pickerBrowser.status = UIViewAnimationAnimationStatusFade;
    
    // 数据源可以不传，传photos数组 photos<里面是ZLPhotoPickerBrowserPhoto>
    pickerBrowser.photos = imgdata;
    // 是否可以删除照片
    pickerBrowser.editing = NO;
    // 当前选中的值
    pickerBrowser.currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    // 展示控制器
    [pickerBrowser showPickerVc:self];
    
    
}

- (IBAction)switchValueChanged:(id)sender {
    if (_isqrcode) {
        return;
    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[user.getmsg intValue ]==1?@"0":@"1" forKey:@"getmsg"];
    [dic setObject:user.id forKey:@"sessionid"];
    [[BusinessService shareInstance]getmsg:dic success:^(id result) {
        [self initdata];
        [SVProgressHUD showSuccessWithStatus:@"设置成功"];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
#pragma  mark 删除并退出
- (IBAction)delAction:(UIButton *)sender {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"确定删除或退出当前群组" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:user.id forKey:@"sessionid"];
        if ([user.role intValue]==1) {
            [[AppDelegate shareDelegate] clearSessionID:user.id typeChat:forChatTypeRoom];//xhw2018-2-5
            
            [[BusinessService shareInstance]gdelete:dic
                                            success:^(id result) {
                                                
                                                UINavigationController *navigationVC = self.navigationController;
                                                NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
                                                //    遍历导航控制器中的控制器
                                                for (UIViewController *vc in navigationVC.viewControllers) {
                                                    [viewControllers addObject:vc];
                                                    if ([vc isKindOfClass:[GroupListVC class]]) {
                                                        break;
                                                    }
                                                }
                                                //    把控制器重新添加到导航控制器
                                                [navigationVC setViewControllers:viewControllers animated:YES];
                                            } failure:^(id result) {
                                                [SVProgressHUD showErrorWithStatus:result];
                                            }];
            
        }else{
            [[BusinessService shareInstance]quit:dic success:^(id result) {
                [[AppDelegate shareDelegate] clearSessionID:user.id typeChat:300]; //xhw2018-1-26加
                [TCSession clearSessionID:user.id typeChat:forChatTypeRoom]; //xhw2018-1-26加
                NSArray* sessionArr = [TCSession getSessionListTimeLine];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"clearSessionGroup" object:nil];
                for (TCSession *session in sessionArr) {
                    NSLog(@"退出了群组->sessionID->%@",session.ID);
                }
                
                UINavigationController *navigationVC = self.navigationController;
                NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
                //    遍历导航控制器中的控制器
                for (UIViewController *vc in navigationVC.viewControllers) {
                    [viewControllers addObject:vc];
                    if ([vc isKindOfClass:[GroupListVC class]]) {
                        break;
                    }
                }
                //    把控制器重新添加到导航控制器
                [navigationVC setViewControllers:viewControllers animated:YES];
            } failure:^(id result) {
                [SVProgressHUD showErrorWithStatus:result];
            }];
        }
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
